<template>
  <div class="medical-records">
    <div class="page-header">
      <h1>就诊记录</h1>
      <p>管理患者就诊记录</p>
    </div>
    
    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="患者姓名">
          <el-input
            v-model="searchForm.patientName"
            placeholder="请输入患者姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="医生姓名" v-if="userStore.isAdmin">
          <el-input
            v-model="searchForm.doctorName"
            placeholder="请输入医生姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="草稿" :value="0" />
            <el-option label="已完成" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 就诊记录列表 -->
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>就诊记录列表</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增记录
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
      >
        <el-table-column prop="recordNo" label="病历编号" width="120" />
        <el-table-column prop="userName" label="患者姓名" width="100" />
        <el-table-column prop="doctorName" label="医生" width="100" />
        <el-table-column prop="departmentName" label="科室" width="120" />
        <el-table-column prop="chiefComplaint" label="主诉" min-width="150" show-overflow-tooltip />
        <el-table-column prop="diagnosis" label="诊断结果" min-width="150" show-overflow-tooltip />
        <el-table-column prop="visitTime" label="就诊时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.visitTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hospitalizationStatus" label="住院状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getHospitalizationStatusType(row.hospitalizationStatus)" v-if="row.needHospitalization">
              {{ getHospitalizationStatusText(row.hospitalizationStatus) }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="床位信息" width="180" align="center">
          <template #default="{ row }">
            <template v-if="row.needHospitalization && row.wardId">
              <el-tooltip
                effect="dark"
                placement="top"
                :content="`${row.wardName || '-'} ${row.bedNumber}号床
科室：${row.departmentName || '-'}`"
              >
                <el-tag type="success">
                  {{ row.wardName || '-' }} - {{ row.bedNumber }}号床
                </el-tag>
              </el-tooltip>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="handleAssignBed(row)"
              v-if="row.needHospitalization && !row.wardId && row.hospitalizationStatus !== 2"
            >
              分配床位
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Document } from '@element-plus/icons-vue'
import { getMedicalRecordList, deleteMedicalRecord } from '@/api/business'
import { addDialog } from '@/components/gDialog'
import medicalRecordHandle from "@/views/adminModal/medicalRecordHandle.vue"
import { useUserStore } from '@/stores/user'
import bedAssignmentHandle from "@/views/adminModal/bedAssignmentHandle.vue"

// 响应式数据
const loading = ref(false)
const tableData = ref([])

// 搜索表单
const searchForm = reactive({
  patientName: '',
  doctorName: '',
  status: null
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 获取用户商店
const userStore = useUserStore()

// 获取就诊记录列表
const fetchMedicalRecords = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      page: pagination.page,
      size: pagination.size
    }
    
    // 过滤空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === null || params[key] === '') {
        delete params[key]
      }
    })
    
    const response = await getMedicalRecordList(params)
    if (response.code === 200) {
      tableData.value = response.data.list || []
      pagination.total = response.data.total || 0
    }
  } catch (error) {
    console.error('获取就诊记录失败:', error)
    ElMessage.error('获取就诊记录失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchMedicalRecords()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'status' ? null : ''
  })
  pagination.page = 1
  fetchMedicalRecords()
}

// 分页相关
const handleSizeChange = (val) => {
  pagination.size = val
  pagination.page = 1
  fetchMedicalRecords()
}

const handleCurrentChange = (val) => {
  pagination.page = val
  fetchMedicalRecords()
}

// 新增就诊记录
const handleAdd = () => {
  addDialog({
    title: '新增就诊记录',
    props: {
      medicalRecord: {},
      isEdit: false
    },
    width: '60%',
    draggable: true,
    fullscreenIcon: true,
    closeOnClickModal: false,
    component: medicalRecordHandle,
     callBack: (result) => {
       if (result === 'success') {
         fetchMedicalRecords()
       }
     }
  })
}

// 查看就诊记录详情
const handleView = (row) => {
  addDialog({
    title: '查看就诊记录',
    props: {
      medicalRecord: { ...row },
      isEdit: true,
      readonly: true
    },
    width: '60%',
    draggable: true,
    fullscreenIcon: true,
    closeOnClickModal: false,
    component: medicalRecordHandle,
    callBack: (result) => {
       if (result === 'success') {
         fetchMedicalRecords()
       }
     }
  })
}

// 编辑就诊记录
const handleEdit = (row) => {
  addDialog({
    title: '编辑就诊记录',
    props: {
      medicalRecord: { ...row },
      isEdit: true
    },
    width: '60%',
    draggable: true,
    fullscreenIcon: true,
    closeOnClickModal: false,
    component: medicalRecordHandle,
    callBack: (result) => {
      if (result === 'success') {
        fetchMedicalRecords()
      }
    }
  })
}

// 删除就诊记录
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确认删除患者 "${row.userName}" 的就诊记录吗？`,
      '删除确认',
      {
        type: 'warning'
      }
    )
    
    await deleteMedicalRecord(row.id)
    ElMessage.success('删除成功')
    fetchMedicalRecords()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'warning',
    1: 'success'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '已完成'
  }
  return statusMap[status] || '未知'
}

// 获取住院状态类型
const getHospitalizationStatusType = (status) => {
  const statusMap = {
    0: 'warning',  // 未住院
    1: 'success',  // 已入院
    2: 'info'      // 已出院
  }
  return statusMap[status] || 'info'
}

// 获取住院状态文本
const getHospitalizationStatusText = (status) => {
  const statusMap = {
    0: '未住院',
    1: '已入院',
    2: '已出院'
  }
  return statusMap[status] || '未知'
}

// 处理分配床位
const handleAssignBed = (row) => {
  addDialog({
    title: '分配床位',
    props: {
      medicalRecord: { ...row }
    },
    width: '500px',
    draggable: true,
    closeOnClickModal: false,
    component: bedAssignmentHandle,
    callBack: (result) => {
      if (result === 'success' || result === true) {
        fetchMedicalRecords()
      }
    }
  })
}

// 初始化
onMounted(() => {
  fetchMedicalRecords()
})
</script>

<style scoped>
.medical-records {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-table .cell) {
  padding: 0 8px;
}
</style> 